package com.situ.object.controll;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 验证码   CaptchaUtil 接口
* */
@WebServlet("/vercode")
public class VercodeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100,38);
        //验证码内容从 baseStr 中选取
        String baseStr = "0123456789";
        RandomGenerator randomGenerator = new RandomGenerator(baseStr,4);
        lineCaptcha.setGenerator(randomGenerator);
        String code = lineCaptcha.getCode();
        //将验证码 code 存放到 session
        req.getSession().setAttribute("code",code);
        //通过字符流将验证码写出
        lineCaptcha.write(resp.getOutputStream());
        resp.getOutputStream().close();
    }
}
